// var _findUserAndAcl = _controller + '/findUserAndAcl';
var RoleComm = {
    Url: CTX + '/sys/role'
};
var RoleMVC = {
    Req: {
        list: {method: 'GET', url: RoleComm.Url},
        add: {method: 'POST', url: RoleComm.Url},
        update: {method: 'PUT', url: RoleComm.Url},
        del: {method: 'DELETE', url: RoleComm.Url},
        export: {method: 'POST', url: RoleComm.Url + '/export'},
        findUserAndAcl : {method: 'GET', url: RoleComm.Url + '/findUserAndAcl'}
    },
    DOMs: null,
    data: {},
    Columns: {
        role: [[{
            field: '_opts_',
            title: '操作',
            width: 100,
            align: 'center',
            formatter: function (v, row, i) {
                var ary = [];
                ary.push('<a href="javascript:;" permission="sys:role:update" class="row-btn" title="修改" onclick="update(' + i + ')"><i class=" fa fa-edit"></i></a>');
                ary.push('<a href="javascript:;" permission="sys:role:del" class="row-btn" title="删除" onclick="deletes(' + i + ')"><i class="fa fa-trash"></i></a>');
                ary.push('<a href="javascript:;" class="row-btn" title="关联信息" onclick="relatedUserAndAcl(' + i + ')"><i class="fa fa-info-circle"></i></a>');
                return ary.join('&nbsp;<span class="btn-separator"></span>&nbsp;');
            }
        }, {
            field: 'name',
            title: '名称',
            width: 120,
            sortable: true,
            formatter: function (v, row, i) {
                return '<a href="javascript:;" class="row-btn" title="' + row.name + '" onclick="see(' + i + ')">' + v + '</a>';
            }
        }, {
            field: 'enname',
            title: '英文名称',
            width: 120
        }, {
            field: 'note',
            title: '备注',
            width: 250
        }, {
            field: 'createTime',
            title: '创建时间',
            width: 150
        }, {
            field: 'updateTime',
            title: '最后修改时间',
            width: 150
        }]]
    }
};

$(function () {
    RoleMVC.DOMs = {
        $searchForm: $('#searchForm'),
        $searchBtn: $('#searchBtn'),
        $resetBtn: $('#resetBtn'),
        $dataGrid: $('#roleGrid'),
        $dlg: $('#dlg')
    };

    initPage(RoleMVC.DOMs, RoleMVC.Req, {
        singleSelect: true,
        sortName: 'id',
        sortOrder: 'asc',
        columns: RoleMVC.Columns.role,
        onSelect: function (index, row) {
            relatedUserAndAcl(index);
        },
        onLoadSuccess: function (data) {
            if (data && data.rows && data.rows.length > 0) {
                $.app.controlPermission();
                $(this).datagrid('selectRow', 0);
            }
        }
    }, getQueryParams, true);

});

function getQueryParams() {
    return RoleMVC.DOMs.$searchForm.serializeForm();
}

function add() {
    var $dlg = RoleMVC.DOMs.$dlg, $grid = RoleMVC.DOMs.$dataGrid;
    var $form = $dlg.find('form');
    $form.form('reset');

    $dlg.dialog({
        title: '新增角色',
        modal: true,
        inline: true,
        buttons: [{
            text: '确定',
            iconCls: 'e-icon fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(RoleMVC.Req.add, formObj, function (roleId) {
                    $grid.datagrid('reload', {
                        id: roleId
                    });
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function update(rowIndex) {
    var $dlg = RoleMVC.DOMs.$dlg, $grid = RoleMVC.DOMs.$dataGrid;
    var row = null;
    if (rowIndex || rowIndex === 0) {// 第0行也可以修改
        $grid.datagrid('unselectAll');
        // $dataGrid.datagrid('selectRow', rowIndex);
        row = $grid.datagrid("getRows")[rowIndex];
    } else {
        row = $grid.datagrid('getSelections')[0];
    }
    if (!row) {
        $.showMsg('请选择一行数据！');
        return;
    }

    var $form = $dlg.find('form');
    $form.form('load', row);
    $dlg.dialog({
        title: '修改角色',
        modal: true,
        buttons: [{
            text: '确定',
            iconCls: 'fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(RoleMVC.Req.update, formObj, function (roleId) {
                    $grid.datagrid('reload', {
                        id: roleId
                    });
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function see(rowIndex) {
    var $dlg = RoleMVC.DOMs.$dlg, $grid = RoleMVC.DOMs.$dataGrid;
    $grid.datagrid('unselectAll');
    // $dataGrid.datagrid('selectRow', rowIndex);

    var role = $grid.datagrid("getRows")[rowIndex];

    $dlg.find('form').form('load', role);
    $dlg.dialog({
        title: '查看角色',
        modal: true,
        buttons: [{
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function deletes(rowIndex) {
    var $grid = RoleMVC.DOMs.$dataGrid;
    if (rowIndex || rowIndex === 0) {// 第0行也可以删除
        $grid.datagrid('unselectAll');
        // $dataGrid.datagrid('selectRow', rowIndex);

        var row = $grid.datagrid("getRows")[rowIndex];
        $.confirmMsg('确定要删除角色[' + row.name + ']吗？', function () {
            doDelete([row.id], $grid);
        });
    } else {
        var rows = $grid.datagrid('getSelections'), ids = [];
        if (rows && rows.length) {
            $.each(rows, function (i, row) {
                ids.push(row.id);
            });
            $.confirmMsg('确定要删除选择的[' + ids.length + ']条记录？', function () {
                doDelete(ids, $grid);
            });
        } else {
            $.showMsg('请选择要删除的记录');
        }
    }
}

function doDelete(ids, $reloadGrid) {
    $.ajax({
        type: RoleMVC.Req.del.method,
        url: RoleMVC.Req.del.url,
        data: {
            ids: ids.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result);
            $reloadGrid.datagrid('reload');
        }
    });
}

function relatedUserAndAcl(rowIndex) {
    var $grid = RoleMVC.DOMs.$dataGrid;
    var role = $grid.datagrid("getRows")[rowIndex];
    var n = $('#roleRelatedLayout').layout('panel', 'north');
    var c = $('#roleRelatedLayout').layout('panel', 'center');
    n.panel('setTitle', '[' + role.name + ']关联用户');
    c.panel('setTitle', '[' + role.name + ']关联权限');
    $.ajax({
        type: RoleMVC.Req.findUserAndAcl.method,
        url: RoleMVC.Req.findUserAndAcl.url,
        data: {
            roleId: role.id
        },
        dataType: 'json',
        success: function (data) {
            if (data && data.status) {
                if (data.status == '200') {
                    var userData = data.data.userList;
                    $('#roleUserGrid').datagrid('loadData', userData);
                    var aclTreeData = data.data.aclTree;
                    aclTreeData = changeTreeGrid2TreeData(aclTreeData, 'id', 'name', 'children');
                    $('#roleAclTree').tree('loadData', aclTreeData);
                } else {
                    $.errorMsg(data.msg);
                }
            }
        }
    });
}
